import { useMemo, useState, useEffect } from "react";
import { useSearchParams, useLocation, useNavigate } from "react-router-dom";
import {
    NavBar,
    Card,
    List,
    Checkbox,
    Button,
    Toast,
    DotLoading,
    ProgressBar,
    Popup,
} from "antd-mobile";
import { Cell } from "react-vant";
import MyTickInfo from "../../components/MyTickInfo";
import { useSelector } from "react-redux";
import http from "../../utils/http";

const Index = () => {
    const navigate = useNavigate();
    const { state } = useLocation();
    const [sq] = useSearchParams();
    const price = sq.get("price");
    const levelseat = sq.get("levelseat");

    //获取仓库上的乘车人数据
    const { tickPersonList } = useSelector((state) => state.TickPersonSlice);
    //获取选中的乘车人数据
    const selectedPerlist = useMemo(() => {
        return tickPersonList.filter((item) => item.state);
    }, [tickPersonList]);

    //模拟订单状态： 1：什么也不做 2：占座中 3：占座失败 4：已占座
    const [tickState, setTickState] = useState(1);
    const [progress, setProgress] = useState(0); //进度条状态
    const [progress2, setProgress2] = useState(0); //进度条状态
    const [visible1, setVisible1] = useState(false);

    useEffect(() => {
        setTickState(2);
        //随机1-10的随机数
        const random = Math.floor(Math.random() * 10) + 1;
        const timer = setInterval(() => {
            setProgress((prev) => {
                let prenum = prev + 20;
                if (prenum >= 100) {
                    prenum = 100;
                    clearInterval(timer);

                    //判断随机数状态
                    if (random > 2) {
                        setTickState(4);
                        Toast.show("占座成功");
                    } else {
                        setTickState(3);
                        Toast.show("占座失败");
                    }
                }

                return prenum;
            });
        }, 800);
    }, []);

    //占座状态进行判断
    const tickStateJSX = useMemo(() => {
        switch (tickState) {
            case 1:
                return <div></div>;
            case 2:
                return (
                    <div>
                        <span>占座中</span>
                        <DotLoading color="primary" />
                    </div>
                );
            case 3:
                return <div>占座失败，重新尝试</div>;
            default:
                return <div>占座成功</div>;
        }
    }, [tickState]);

    //支付
    const handelPay = async () => {
        const res = await http.get("/api//pay", {
            params: {
                id: state.id,
                title: "系统购票",
                price: price,
            },
        });
        const { code, data } = res.data;
        if (code === 200) window.location.href = data;

        //查询订单状态：是否成功
        const payTimer = setInterval(async () => {
            //查询订单状态，请求接口
            const res2 = await http.get("/api/query", { params: { id: state.id } });
            const { code } = res2.data;
            console.log(res2.data);
            if (code === 200) {
                clearInterval(payTimer);
                Toast.show("支付成功，正在出票...");
                navigate("/success");
            } else {
                Toast.show("支付失败");
                clearInterval(payTimer);
                navigate("/orderconfirm");
            }
        }, 3000);
    };

    return (
        <div>
            <NavBar onBack={() => navigate(-1)}>订单确认-占座</NavBar>
            <MyTickInfo data={state} />
            <div>
                <ProgressBar
                    percent={progress}
                    style={{
                        "--track-width": "4px",
                    }}
                />
                {tickStateJSX}
                <Card>
                    <List>
                        {selectedPerlist.map((item, ind) => (
                            <List.Item
                                key={ind}
                                description={item.code}
                                extra={
                                    <div>
                                        <p>{tickStateJSX}</p>
                                        <Checkbox checked={item.state} />
                                    </div>
                                }
                            >
                                {item.name}
                            </List.Item>
                        ))}
                    </List>
                </Card>
                <Cell title="订单号：" value={state.id} />
                <Cell title="订单标题：" value={"火车票-" + levelseat} />
                <Cell title="订单金额：" value={"￥" + price} />
            </div>
            <Button
                block
                color="primary"
                size="large"
                disabled={tickState != 4}
                onClick={() => {
                    setVisible1(true);
                    setTimeout(() => {
                        setProgress2(100);
                    }, 3000);
                }}
            >
                确认下单
            </Button>

            <Popup
                visible={visible1}
                onMaskClick={() => {
                    setVisible1(false);
                }}
                onClose={() => {
                    setVisible1(false);
                }}
            >
                <ProgressBar
                    percent={progress2}
                    style={{
                        "--track-width": "4px",
                    }}
                />
                <MyTickInfo data={state} />
                <Button onClick={() => handelPay()} block color="primary" size="large">
                    支付宝
                </Button>
                <Button block color="success" size="large">
                    微信支付
                </Button>
                <Button block color="danger" size="large">
                    云闪付
                </Button>
            </Popup>
        </div>
    );
};

export default Index;